
const wrapper = document.getElementById("signature-pad")
const clearButton = wrapper.querySelector("[data-action=clear]")
const savePNGButton = wrapper.querySelector("[data-action=save-png]")
const tuichu = wrapper.querySelector("[data-action=tuichu]")
const canvas = wrapper.querySelector("canvas")

// 获取查询字符串，去掉问号
const queryString = window.location.search.substring(1);
// 将查询字符串分割成参数数组
const params = queryString.split('&');
// 创建一个对象来存储所有参数
const queryParams = {};
// 遍历参数数组
for (let i = 0; i < params.length; i++) {
  // 分割每个参数为键值对
  const param = params[i].split('=');
  // 解码URI组件，并将它们添加到queryParams对象中
  queryParams[param[0]] = decodeURIComponent(param[1]);
}
const id = queryParams['id'];
const type = queryParams['type'];


const signaturePad = new SignaturePad(canvas, {
  // It's Necessary to use an opaque color when saving image as JPEG
  // this option can be omitted if only saving as PNG or SVG
  backgroundColor: 'rgb(255, 255, 255)'
})

const resizeCanvas = () => {
  const ratio = Math.max(window.devicePixelRatio || 1, 1)
  canvas.width = canvas.offsetWidth * ratio
  canvas.height = canvas.offsetHeight * ratio
  canvas.getContext("2d").scale(ratio, ratio)
  signaturePad.clear()
}

// On mobile devices it might make more sense to listen to orientation change,
// rather than window resize events.
window.onresize = resizeCanvas
resizeCanvas()

const download = (dataURL, filename) => {
  const blob = dataURLToBlob(dataURL)
  const url = window.URL.createObjectURL(blob)

  const a = document.createElement("a")
  a.style = "display: none"
  a.href = url
  a.download = filename

  document.body.appendChild(a)
  a.click()

  window.URL.revokeObjectURL(url)
}

// One could simply use Canvas#toBlob method instead, but it's just to show
// that it can be done using result of SignaturePad#toDataURL.
function dataURLToBlob(dataURL) {
  // Code taken from https://github.com/ebidel/filer.js
  const parts = dataURL.split('base64,')
  const contentType = parts[0].split(":")[1]
  const raw = window.atob(parts[1])
  const rawLength = raw.length
  const uInt8Array = new Uint8Array(rawLength)

  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }

  return new Blob([uInt8Array], { type: contentType })
}

clearButton.addEventListener("click", () => signaturePad.clear())



savePNGButton.addEventListener("click", () => {
  if (signaturePad.isEmpty()) {
    alert("Please provide a signature first.")
  } else {
    const dataURL = signaturePad.toDataURL('image/png');
    const blob = dataURLToBlob(dataURL);

    // 创建 FormData 对象并添加文件
    const formData = new FormData();
    formData.append('upfile', blob, 'signature.png');
    const url = 'https://www.csxgw.com/Scripts/UEditor/net/controller.ashx?action=uploadimage';
    // 使用 fetch API 上传图片
    fetch(url, {
      method: 'POST',
      body: formData
    }).then(response => response.json()).then(data => {
      Getcontract(data)
    }).catch(error => {
      console.error('An error occurred during the upload:', error);
    });
    // download(dataURL, "signature.png")
  }
})
tuichu.addEventListener("click", () => {
  window.history.back();
})

//提交信息
function Getcontract(data) {
  console.log(data);
  var Imgurl = data.url;
  const url = 'https://www.csxgw.com/api/WeChatAPI/UpdateContract';
  // 构造请求体
  const contractData = {
    id: id,
    photo: Imgurl,
    type: type
  };
  if (Imgurl) {
    $.post(url, contractData, function (res) {
      console.log();
      var data = JSON.parse(res);
      if (data.isOk == true) {
        alert('签名成功')
        window.history.back();
      } else {

      }
    });
  }

}